package org.aeon.server.handler.Inbound;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.aeon.entity.dto.UserVerificationDto;
import org.aeon.message.request.CancelLoginRequestMessage;
import org.aeon.message.request.LoginRequestMessage;
import org.aeon.message.request.RegisterRequestMessage;
import org.aeon.message.request.RequestMessage;
import org.aeon.message.response.IllegalRequestResponseMessage;
import org.aeon.message.response.RequestLoginResponseMessage;
import org.aeon.service.factory.SessionFactory;
import org.aeon.service.factory.UserServiceFactory;

/**
 * @author: MissingAeon
 * @date: 2024/1/27 13:09
 * @description: 请求验证
 */
@Slf4j
@ChannelHandler.Sharable
public class RequestHandler extends SimpleChannelInboundHandler<RequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RequestMessage msg) throws Exception {
        if (msg instanceof CancelLoginRequestMessage) {
            ctx.fireChannelRead(msg);
            return;
        }
        // 检查token
        if (msg.getToken() != null) {
            // 匹配token
            final Long userId = SessionFactory.getSession().getUserId(ctx.channel());
            final String token = UserServiceFactory.getService().checkTokens(userId);
            if (token != null) {
                if (token.equals(msg.getToken())) {
                    ctx.fireChannelRead(msg);
                    return;
                }
            }
        }
        // 没有token则检查用户验证消息
        final UserVerificationDto userV = msg.getUserVerification();
        // 没有token和验证信息的请求
        if (userV == null) {
            final Long userId = SessionFactory.getSession().getUserId(ctx.channel());
            // 同时也没有绑定用户id
            if (userId == null) {
                ctx.writeAndFlush(new IllegalRequestResponseMessage());
                ctx.channel().close();
            } else {
                final RequestLoginResponseMessage responseMessage = new RequestLoginResponseMessage();
                responseMessage.setRequestMessage(msg);
                ctx.writeAndFlush(responseMessage);
            }
        } else {
            // 重新返回token
            ctx.fireChannelRead(new LoginRequestMessage(userV));
            // 验证通过
            ctx.fireChannelRead(msg);
        }

    }

}
